package com.app.web.order;

import com.app.base.BaseParam;
import com.app.base.EnumType;
import com.app.utils.base.j2se.Convert;
import com.app.utils.base.j2se.DateUtil;
import com.app.utils.base.j2se.StringHandler;
import com.app.utils.spring.config.SystemError;
import com.app.utils.spring.properties.Config;
import com.app.utils.web.Param;
import com.app.web.goods.goods.GoodsDao;
import com.app.web.jst.Order;
import com.app.web.user.info.UserInfo;
import com.app.web.user.myCenter.MyCenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: tbyy-app->OrderService
 * @Auther: 王伟
 * @Date: 2019/12/13 11:23
 * @Description:订单
 */
@Service
public class OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private MyCenterService myCenterService;

    /**
     * 生成订单信息并进行支付
     * @param type 1钱包支付， 2在线支付
     * @param userInfo
     * @param goods
     * @param num   购买数量
     * @param units 商品规格
     * @param money 购买总金额
     * @param address_id 快递地址id
     */
    @Transactional
    public long order(int type,UserInfo userInfo,Map<String,Object> goods,int num,String units,int money,int address_id,int payChannel){
        Map<String,Object> order = new HashMap<String,Object>(){{
            put("order_sn", BaseParam.getOrderSN());
            put("order_amount", money);
            put("date", DateUtil.getDate());
            put("goods_id",goods.get("id"));
            put("goods_name",goods.get("name"));
            put("goods_pic",goods.get("cover_pic"));
            put("goods_category_pid",goods.get("category_pid"));
            put("goods_units",units);
            put("goods_price",goods.get("price"));
            put("goods_inner_price",goods.get("inner_price"));
            put("goods_num",num);
            put("goods_is_discount",goods.get("is_discount"));
            put("uid",userInfo.getUid());
            put("role",userInfo.getRole());
            put("address_id",address_id);
            put("type",type);
            put("payChannel",payChannel);
        }};
        orderDao.order(order);
        int goodsCount = goodsDao.goodsInventoryChange(Convert.objToInt(goods.get("id")),num);
        if(goodsCount!=1) SystemError.wrapBs("6001","商品库存不足");
//        if(type==1){
//            int count = walletDao.subtractUserMoney(order);
//            if(count!=1)SystemError.wrapBs("6001","钱包余额不足");
//        }
        /* 线程池开启 */
//        new Thread(()->{
//            /* 发送微信推送，告知商家有新的订单 */
//            try {
//                WxMaSubscribeMessage message = new WxMaSubscribeMessage();
//                message.setTemplateId(Config.pp.get("order.new.subscribe.templateId"));
//                message.addData(new WxMaSubscribeMessage.Data("thing1",Convert.objToStr(goods.get("name"))));
//                message.addData(new WxMaSubscribeMessage.Data("thing4","您有新的订单，请注意查重！"));
//                String[] peoples = Convert.objToStr(MerchantManager.getMerchantById(Convert.objToInt(merchant.get("id"))).get("people")).split(",");
//                for (String people : peoples) {
//                    message.setToUser(people);
//                    AppInfoManager.get("wxb759ea4afaee0095").getWxMaService().getMsgService().sendSubscribeMsg(message);
//                }
//            } catch (WxErrorException e) {
//                Logger.error("预约后发送微信订阅消息失败",e);
//                e.printStackTrace();
//            }
//        }).start();
        return Convert.objToLong(order.get("id"));
    }

    @Transactional
    public void orderChange(String order_sn){
        //修改订单状态
        orderDao.orderChange(EnumType.ORDER_STATUS.确认收货.getStatus(), Collections.singletonList(order_sn));
        //确认收货修改订单分佣明细表状态,
        orderDao.orderExceptChange(EnumType.ORDER_STATUS.确认收货.getStatus(), order_sn);
    }

    @Transactional
    public void cancelApply(long uid,int order_status,String order_sn,String reason){
        //记录退货申请
        orderDao.cancelApply(uid,order_status, order_sn, reason);
        //修改订单状态与订单分佣状态
        int count = orderDao.orderChange(EnumType.ORDER_STATUS.申请退货.getStatus(), Collections.singletonList(order_sn));
        if(count == 0)SystemError.wrapBs("6001","订单异常，请联系管理员");
//        count = orderDao.orderExceptChange(EnumType.ORDER_STATUS.申请退货.getStatus(), order_sn);
//        if(count == 0)SystemError.wrapBs("6001","订单正在处理中，暂时无法申请退款，请稍后再来！");
    }

    @Transactional
    public void cancel(long uid,String order_sn,String express_name,String express_no){
        //记录退货信息
        int count = orderDao.cancel(order_sn, express_name,express_no);
        if(count!=1)SystemError.wrapBs("6001","快递信息提交失败，请联系管理员！");
        count = orderDao.orderChange(EnumType.ORDER_STATUS.待退款.getStatus(), Collections.singletonList(order_sn));
        if(count!=1)SystemError.wrapBs("6001","快递信息提交失败，请联系管理员！！");
    }

    //退货退款-订单信息
    public Map<String,Object> getOrder(String order_sn){
        Map<String,Object> map = orderDao.getOrder(order_sn);
        //组装商品图
        String url = Param.picUrl;
        if(Convert.objToStr(map.get("goods_pic")).startsWith("http")){
            url = "";
        }
        map.put("goods_pic",url+Convert.objToStr(map.get("goods_pic")).trim());
        //申请过的订单，同时查询出来退款申请数据
        if(Convert.objToInt(map.get("status"))>=EnumType.ORDER_STATUS.申请退货.getStatus()){
            Map<String,Object> cancel = orderDao.getOrderCancel(order_sn);
            cancel.put("cancel_sn",DateUtil.paseDatetime(Convert.objToStr(cancel.get("cancel_time"))).getTime()/1000);
            map.putAll(cancel);
        }
        int status = StringHandler.getInt(map.get("status"));
        map.put("order_status",status);
        map.put("status_name",EnumType.ORDER_STATUS.getName(status));
        //同意退货还没有填写快递信息的，获取商家收获信息
//        if(Convert.objToInt(map.get("status"))==EnumType.ORDER_STATUS.同意退货.getStatus() && Convert.objToInt(map.get("cancel_status"))==0){
//            String addr = Convert.objToStr(MerchantManager.getMerchantById(Convert.objToInt(map.get("merchant_id"))).get("expressJson"));
//            Map<String,Object> cancelAddr = JSON.parseObject(addr).getInnerMap();
//            map.put("cancel_name",cancelAddr.get("name"));
//            map.put("cancel_phone",cancelAddr.get("phone"));
//            map.put("cancel_address",cancelAddr.get("address"));
//        }
        return map;
    }

    public List<Map<String,Object>> orderListByUid(long uid,int status,int page){
        int rows = Convert.objToInt(Config.pp.get("list.search.limit.max"));
        int pageNumber = (page-1)*rows;
        Map<String,Object> map = new HashMap<>();
        map.put("uid",uid);
        map.put("status",status);
        map.put("pageNumber",pageNumber);
        map.put("rows",rows);
        return orderDao.getUidOrderList(map);
    }

    /**
     * 订单列表
     * @param uid
     * @param status
     * @param page
     * @return
     */
    public List<Map<String,Object>> getOrderList(long uid,int status,int page){
        int rows = Convert.objToInt(Config.pp.get("list.search.limit.max"));
        int pageNumber = (page-1)*rows;
        Map<String,Object> map = new HashMap<>();
        map.put("uid",uid);
        map.put("status",status);
        map.put("pageNumber",pageNumber);
        map.put("rows",rows);
        return orderDao.getOrderList(map);
    }

    /**
     * 生成订单信息并进行支付（聚水潭）
     * @param type 1钱包支付， 2在线支付
     * @param userInfo
     * @param num   购买数量
     * @param units 商品规格
     * @param money 购买总金额
     * @param address_id 快递地址id
     */
    @Transactional
    public long orderJst(int type,UserInfo userInfo,String goods_name,String goods_pic,int num,
                         String units,long money,long address_id,int payChannel,String sku_id){
        Map<String,Object> order = new HashMap<String,Object>(){{
            put("order_sn", BaseParam.getOrderSN());
            put("order_amount", money);
            put("date", DateUtil.getDate());
            put("goods_id",0);
            put("goods_name",goods_name);
            put("goods_pic",goods_pic);
            put("goods_category_pid",0);
            put("goods_units",units);
            put("goods_price",money);
            put("goods_inner_price",money);
            put("goods_num",num);
            put("goods_is_discount",2);
            put("uid",userInfo.getUid());
            put("role",userInfo.getRole());
            put("address_id",address_id);
            put("type",type);
            put("payChannel",payChannel);
            put("source",2);
            put("sku_id",sku_id);
        }};
        orderDao.orderJst(order);
        return Convert.objToLong(order.get("id"));
    }

    public Map<String,Object> getOrderInfo(long id){
        return orderDao.getOrderInfo(id);
    }

    public Map<String,Object> addrInfo(long uid, long id){
        return orderDao.addrInfo(uid,id);
    }
}
